package com.umakr.ax.scheduler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 调度监听器
 *
 * @author umakr
 */
public class JobListener implements org.quartz.JobListener {
	protected final Log logger = LogFactory.getLog(this.getClass());
	public interface JobCallback{
		/**
		 * onBeforeJobExecute
		 * @param targetObject
		 * @param targetMethod
		 */
		void onBeforeJobExecute(String targetObject, String targetMethod);

		/**
		 * onAfterJobExecute
		 * @param targetObject
		 * @param targetMethod
		 * @param exp
		 */
		void onAfterJobExecute(String targetObject, String targetMethod, JobExecutionException exp);
	}
	@Autowired
	private SchedulerService schedulerService;
	/**
	 * 线程池
	 */

	private JobCallback jobCallback;



	@Override
	public String getName() {
		return "taskListener";
	}

	public JobCallback getJobCallback() {
		return jobCallback;
	}

	public void setJobCallback(JobCallback jobCallback) {
		this.jobCallback = jobCallback;
	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
		// Do nothing because of X and Y.
	}

	/**
	 * 任务开始前
	 * @param context
	 */
	@Override
	public void jobToBeExecuted(final JobExecutionContext context) {
		final JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		String targetObject = jobDataMap.getString("targetObject");
		String targetMethod = jobDataMap.getString("targetMethod");
		if(jobCallback != null){
			jobCallback.onBeforeJobExecute(targetObject,targetMethod);
		}
	}

	/**
	 * 任务结束后
	 * @param context
	 * @param exp
	 */
	@Override
	public void jobWasExecuted(final JobExecutionContext context, JobExecutionException exp) {
		final JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		String targetObject = jobDataMap.getString("targetObject");
		String targetMethod = jobDataMap.getString("targetMethod");

		if(jobCallback != null){
			jobCallback.onAfterJobExecute(targetObject,targetMethod,exp);
		}
	}

}
